package com.xyh.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xyh.dao.TagMapper;
import com.xyh.exception.NotFoundException;
import com.xyh.pojo.PageRequest;
import com.xyh.pojo.PageResult;
import com.xyh.pojo.PageUtils;
import com.xyh.pojo.Tag;
import com.xyh.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

@Service
public class TagServiceImpl implements TagService {
    @Autowired
    private TagMapper tagMapper;
    @Transactional
    @Override
    public int save(Tag tag) {
        return tagMapper.save(tag);
    }

    @Transactional
    @Override
    public Tag getTag(Long id) {
        return tagMapper.findOne(id);
    }

    @Transactional
    @Override
    public int updateTag(Long id, Tag tag) {
        Tag t = tagMapper.findOne(id);
        if (t == null) {
            throw new NotFoundException("不存在该分类");
        }
        return tagMapper.update(id,tag);
    }

    @Transactional
    @Override
    public int delete(Serializable id) {
        return tagMapper.delete(id);
    }

    /**
     * 调用分页插件完成分页
     * @param pageRequest 自定义，统一分页查询请求
     * @return 分页结果
     */
    @Override
    public PageResult getPage(PageRequest pageRequest) {
        int pageNum = pageRequest.getPageNum();
        int pageSize = pageRequest.getPageSize();
        PageHelper.startPage(pageNum, pageSize);
        List<Tag> tagList = tagMapper.getAll();
        PageInfo<Tag> pageInfo = new PageInfo<>(tagList);
        return PageUtils.getPageResult(pageInfo);
    }

    @Override
    public Tag getTagByName(String name) {
        return tagMapper.getTagByName(name);
    }

    @Override
    public List<Tag> getAll() {
        return tagMapper.getAll();
    }

    @Override
    public List<Tag> getTagInIds(String ids) {
        String[] split = ids.split(",");
        return tagMapper.getTagInIds(split);
    }

    @Override
    public List<Tag> getTagTop(Integer size) {
        return tagMapper.getTagTop(size);
    }
}
